﻿using EntityModels.Configures;
using EntityModels.Entities;
using Microsoft.EntityFrameworkCore;

namespace EntityModels.DbContexts
{
    /// <summary>
    /// 基于Fluent API的配置
    /// </summary>
    public class BasicEntityDbContext : DbContext
    {
        public DbSet<SimpleEntity> SimpleEntities => Set<SimpleEntity>();
        public DbSet<UserEntity> UserEntities => Set<UserEntity>();

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 风格一
            // 取出实体配置器
            var simpleEntityBuilder = modelBuilder.Entity<SimpleEntity>();
            simpleEntityBuilder.ToTable("CustomTableName", "dbo")
                .HasKey(s => s.Id);

            simpleEntityBuilder.Property(s => s.SimpleEntityId).UseIdentityColumn(1, 1);

            simpleEntityBuilder.Property(s => s.NullableStruct).HasColumnName("CustomColumnName").HasColumnType("int");

            simpleEntityBuilder.Property(s => s.Text).IsRequired().HasMaxLength(50);

            simpleEntityBuilder.Property(s => s.DecimalNumber).HasPrecision(16, 4);


            // 风格二
            modelBuilder.Entity<SimpleEntity>(b =>
            {
                b.ToTable("CustomTableName", "dbo").HasKey(s => s.SimpleEntityId);

                b.Property(s => s.SimpleEntityId).UseIdentityColumn(1, 1);

                b.Property(s => s.NullableEnum).HasColumnName("CustomColumnName").HasColumnName("int");

                b.Property(s => s.Text).IsRequired().HasMaxLength(50);

                b.Property(s => s.DecimalNumber).HasPrecision(16, 4);
            });

            modelBuilder.Entity<UserEntity>(u =>
            {
                u.ToTable("UserEntity").HasKey(s => s.Id);
                u.Property(s => s.UserId).UseIdentityColumn(1, 1);
                u.Property(s => s.Name).IsRequired();
                u.Property(s => s.Email).IsRequired();
                u.Property(s => s.Password).IsRequired();
            });

            modelBuilder.ApplyConfiguration(new SimpleEntityConfiguration());

            modelBuilder.ApplyConfiguration(new UserEntityConfiguration());

        }
    }
}
